package com.example.databasepj.service;

import com.example.databasepj.Request.MerchantUpdateRequest;
import com.example.databasepj.Request.UserReviewMerchantRequest;
import com.example.databasepj.dto.*;
import com.example.databasepj.entity.DishEntity;
import com.example.databasepj.entity.MerchantEntity;
import com.example.databasepj.entity.MerchantReviewEntity;
import com.example.databasepj.mapper.*;
import org.apache.ibatis.exceptions.PersistenceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MerchantService {
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private DishMapper dishMapper ;
    @Autowired
    private MerchantReviewMapper merchantReviewMapper;
    @Autowired
    private DishReviewMapper dishReviewMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserStarDishMapper userStarDishMapper;

    public MerchantEntity selectMerchantByName(String name){
        return merchantMapper.selectMerchantByName(name);
    }

    public MerchantEntity selectMerchantById(int id){
        return merchantMapper.selectMerchantById(id);
    }

    //用户搜索商户
    public ExistResponse userSearchMerchant(String name){
        MerchantEntity merchantEntity = merchantMapper.selectMerchantByName(name);
        if(merchantEntity != null){
            return new GetMerchantInfoResponse(true,merchantEntity.getMerchant_id());

        }
        else {
            return new NotExistResponse(false);
        }

    }

    //用户查看商户详细信息
    public MerchantInfo getMerchantDetail(int id){
        MerchantEntity merchantEntity = selectMerchantById(id);
        if(merchantEntity != null){
            return new MerchantInfo(merchantEntity.getMerchant_id(),merchantEntity.getMerchant_name(),merchantEntity.getAddress());

        }
        else {
            return new MerchantInfo();
        }

    }

    //用户查看商户简略信息
    public MerchantBrief getMerchantBrief(int id){
        MerchantEntity merchantEntity = selectMerchantById(id);
        List<DishEntity> signatureDishes = dishMapper.selectDishByMerchantIdAndSignature(id);
        List<DishBriefInfo> dishLists=new ArrayList<>();
        for (int i=0;i<signatureDishes.size();i++){
            DishEntity dish=signatureDishes.get(i);
            dishLists.add(new DishBriefInfo(dish.getDish_id(),dish.getDish_name()));
        }
        MerchantBrief merchantBrief = new MerchantBrief(merchantEntity.getMerchant_id(), merchantEntity.getMerchant_name(),dishLists);
        return merchantBrief;
    }

    //查看商家菜单
    public List<DishMenuData> getMerchantMenu(int id){
        List<DishEntity> dishEntities=dishMapper.selectDishByMerchantId(id);
        List<DishMenuData> menuDataList = new ArrayList<>();
        for (int i=0;i<dishEntities.size();i++){
            DishEntity dish=dishEntities.get(i);
            DishMenuData dishMenuData = new DishMenuData(dish.getDish_id(), dish.getDish_name(),dish.getPrice());
            //"starNum": 12, // 收藏量

            Integer starNum= userStarDishMapper.countStarNumByDishId(dishMenuData.getDish_ID());
            if(starNum == null) starNum=0;
            dishMenuData.setStarNum(starNum);
            //      "salesVolume_online": 1，// 0: 排队点餐, 1: 在线点餐
            Integer salesVolume_online = orderDetailMapper.countOnlineByDishID(dishMenuData.getDish_ID());
            if(salesVolume_online==null)  salesVolume_online=0;
            dishMenuData.setSalesVolume_online(salesVolume_online);
            // "salesVolume_offline": 2 // 0: 排队点餐, 1: 在线点餐
            Integer salesVolume_offline = orderDetailMapper.countOfflineByDishID(dishMenuData.getDish_ID());
            if(salesVolume_offline==null) salesVolume_offline=0;
            dishMenuData.setSalesVolume_offline(salesVolume_offline);

            menuDataList.add(dishMenuData);
        }
        return menuDataList;
    }

    //查看商户评价
    public List<MerchantReviewResponse> GetMerchantReview(int id){
        List<MerchantReviewEntity> merchantReviewEntities = merchantReviewMapper.selectMerchantReviewByMerchantID(id);
        List<MerchantReviewResponse> merchantReviewResponseList=new ArrayList<>();
        for (int i=0;i<merchantReviewEntities.size();i++){
            MerchantReviewEntity review =merchantReviewEntities.get(i);
            merchantReviewResponseList.add(new MerchantReviewResponse(review.getMerchant_review_id(),review.getUser_id(), review.getRating(), review.getComment()));
        }
        return merchantReviewResponseList;
    }

    //插入商家评价
    public UserReviewMerchantResponse insertMerchantReview(UserReviewMerchantRequest reviewMerchantRequest){
        //获取商家的完整信息
        MerchantEntity newMerchant = merchantMapper.selectMerchantById(reviewMerchantRequest.getMerchant_ID());
        MerchantReviewEntity merchantReviewEntity = new MerchantReviewEntity();
        merchantReviewEntity.setMerchant_id(reviewMerchantRequest.getMerchant_ID());
        merchantReviewEntity.setOrder_id(reviewMerchantRequest.getOrder_ID());
        merchantReviewEntity.setUser_id(reviewMerchantRequest.getUser_ID());
        merchantReviewEntity.setRating(reviewMerchantRequest.getRating());
        merchantReviewEntity.setComment(reviewMerchantRequest.getComment());

        //如果该订单已经评价过，则更新订单
        MerchantReviewEntity merchantReview = merchantReviewMapper.selectMerchantReviewByOrderID(reviewMerchantRequest.getOrder_ID());
        if(merchantReview != null){
            //更新订单
            //merchantReviewEntity.setMerchant_review_id();
            merchantReviewMapper.updateMerchantReview(merchantReviewEntity);
            //返回结果
            return new UserReviewMerchantResponse("success","该订单已评价过，评价更新成功");

        }

        //如果该订单未评价过
        try{
            merchantReviewMapper.insertMerchantReview(merchantReviewEntity);
            return new UserReviewMerchantResponse("success","评价提交成功");

        }catch(PersistenceException e){
            return new UserReviewMerchantResponse("fail","评价提交失败");
         //   throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }
    //商家获取菜单和分析数据
    public List<MerchantGetMenu> merchantGetMenuAndData(int merchantId){
        List<MerchantGetMenu> results =new ArrayList<>();
        //先搜索merchant中dish信息
        List<DishEntity> dishEntities = dishMapper.selectDishByMerchantId(merchantId);
        //对每一个dish做数据分析
        for(int i=0;i<dishEntities.size();i++){
            DishEntity dishEntity = dishEntities.get(i);
            MerchantGetMenu dish = new MerchantGetMenu(dishEntity.getDish_id(),dishEntity.getDish_name(),dishEntity.getDish_category(),dishEntity.getPrice(),dishEntity.getDescription(),dishEntity.getIngredient(),dishEntity.getNutritionInfo(),dishEntity.getAllergen(), dishEntity.getIsSignatureDish());
            // private float average_rating; // 菜品的平均评分
            Float aveRating=dishReviewMapper.getAverageRating(dish.getDish_ID());
            if(aveRating == null){
                dish.setAverage_rating(0);
            }
            else {
                dish.setAverage_rating(aveRating);
            }

            //    private int total_sales;// 销量
            Integer total_sales= orderDetailMapper.getTotalSalesByDishId(dish.getDish_ID());
            if(total_sales==null){
                dish.setTotal_sales(0);
            }else {
                dish.setTotal_sales(total_sales);
            }
            //    private int top_customer_ID;// 购买最多的人
            Integer top_customer_ID= orderDetailMapper.getTopPurchaserByDishId(dish.getDish_ID());
            if(top_customer_ID==null){
                dish.setTop_customer_ID(0);
            }else {
                dish.setTop_customer_ID(top_customer_ID);
            }
            results.add(dish);
        }

        return results;
    }

    public void updateMerchantInfo(int merchantID, MerchantUpdateRequest request){
        MerchantEntity merchantEntity = new MerchantEntity(merchantID,request.getMerchant_name(), request.getAddress(), request.getPassword());
        merchantMapper.updateMerchant(merchantEntity);
    }

    public MerchantCompleteInfo getMerchantCompleteInfo(int merchantId){
        MerchantEntity merchantEntity = merchantMapper.selectMerchantById(merchantId);
        MerchantCompleteInfo merchantInfo = new MerchantCompleteInfo(merchantEntity.getMerchant_id(), merchantEntity.getMerchant_name(),merchantEntity.getAddress(),merchantEntity.getPassword());
        return merchantInfo;
    }

}


